package com.dimong.loan.sdk.ui.adapter;

import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.dimong.loan.sdk.ui.adapter.interfaces.AdapterInterface;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseListAdapter<T> extends BaseAdapter implements AdapterInterface<T> {
    protected final String TAG = getClass().getSimpleName();
    protected List<T> mData;
    protected LayoutInflater mInflater;
    protected Context mContext;

    public BaseListAdapter(Context context) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public Object getItem(int position) {
        if (position < 0) {
            return null;
        }
        return mData == null ? null : mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ListViewHolder holder = null;
        if (convertView == null || convertView.getTag() == null) {
            convertView = mInflater.inflate(getItemLayoutResId(position), null);
            convertView.setTag(holder);
        } else {
            holder = (ListViewHolder) convertView.getTag();
        }
        getView(convertView, holder, position);
        return convertView;
    }

    protected abstract int getItemLayoutResId(int position);

    protected abstract void getView(View convertView, ListViewHolder holder, int position);

    @Override
    public void setData(List<T> data) {
        this.mData = data;
    }

    @Override
    public List<T> getData() {
        return mData;
    }

    @Override
    public void addData(T data) {
        if (mData == null) {
            mData = new ArrayList<T>();
        }
        mData.add(data);
    }

    @Override
    public void addDataList(List<T> data) {
        if (mData == null) {
            mData = new ArrayList<T>();
        }
        mData.addAll(data);
    }

    @Override
    public void clear() {
        if (mData == null) {
            return;
        }
        mData.clear();
    }

    @Override
    public void updateChange() {
        notifyDataSetChanged();
    }

    @Override
    public void removeItem(int position) {
        if (mData != null && mData.size() > position) {
            mData.remove(position);
        }
    }

    public Resources getResources() {
        return mContext.getResources();
    }
}
